package Entities;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.swing.JOptionPane;

import org.hibernate.*;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import utils.HibernateUtil;
import Interface.Accueil;
import Interface.index;

public class Identification {

        private boolean connection = false;
        private Users user;

        public Identification(Hashtable identifiant, index login){
                Session session = HibernateUtil.currentSession();
                try{

                        String login_tmp = identifiant.get("login").toString();
                        String password_tmp = identifiant.get("password").toString();
                        MD5 chaine = new MD5();
                        password_tmp = chaine.encode(password_tmp);

                        Criteria criteria  = session.createCriteria(Users.class);
                        criteria.add(Restrictions.eq("email",login_tmp));
                        criteria.add(Restrictions.eq("Password",password_tmp));
                        List userResult = criteria.list();
                        if(userResult !=null)
                        {
                          for (Iterator it = userResult.iterator() ; it.hasNext();)
                          {
                                Users result =(Users) it.next();
                                connection = true;
                                user = result;
                          }
                        }

                    if(connection) {
                    	/*Date date_obj = new Date();
                    	DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd hh':'mm");
       				 	String date = dateFormat.format(date_obj);
                    	Transaction tx = session.beginTransaction();
                        Logs l = new Logs();
                        l.setDate(date.toString());
                        l.setDescription("Connexion a l'accueil d'Heol : " + user.getEmail());
                        l.setType("Identification");
                        l.setUsersId(user.getIdUser());
                        session.persist(l);
       				 	tx.commit();*/
       				 	
       				 	Hashtable recap = new Hashtable();
       				 	recap.put("login", login_tmp); 
       				 	recap.put("password", password_tmp);
       				 	
       				    Accueil acceuil = new Accueil(recap);
                        login.dispose();
                    }else {
        		    	JOptionPane.showMessageDialog(null, "Connexion refusee","Etat de la connexion",JOptionPane.ERROR_MESSAGE);
        		    }

                       
                }catch(Exception e){
                     //System.out.println("Error : "+e);
                }
                
                //session.close();
        }
}
